<script setup lang="ts">
import { createConsultOrder, getConsultOrderPayUrl, getConsultOrderPre } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore } from '@/stores'
import type { ConsultOrderPreData, PartialConsult } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showLoadingToast, showToast } from 'vant'
import { onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'

const store = useConsultStore()

// 获取支付信息
const payInfo = ref<ConsultOrderPreData>()
const getPayINfo = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type,
    illnessType: store.consult.illnessType,
  })
  payInfo.value = res.data
  if (res.data.couponId) {
    // 设置优惠券
    store.setCouponId(res.data.couponId)
  }
}
// 获取患者用户信息
const userInfo = ref<Patient>()
const getUserInfo = async () => {
  if (!store.consult.patientId) return
  const res = await getPatientDetail(store.consult.patientId)
  userInfo.value = res.data
}

const showActionSheet = ref(false)
// 支付方式
const selectedPayType = ref<0 | 1>(0) // wechat alipay

// 提交表单
const isLoading = ref(false)
const agree = ref(false)
const orderId = ref('') // 后端返回的订单id
const onSubmit = async () => {
  if (!agree.value) {
    return showToast('请同意支付协议')
  }
  showActionSheet.value = true
  isLoading.value = true

  // 生成订单并获取订单id
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id
  isLoading.value = false

  // 清除本地的订单信息
  store.clearConsult()
}

// 阻止用户关闭支付页面
// 知识点【路由守卫】：onBeforeRouteLeave 导航守卫， 作用：阻止用户关闭当前路由。一般用来做用户表单未保存中途退出（比如点返回）的提示
onBeforeRouteLeave(() => {
  //知识点： 如果生成了订单，就阻止用户关闭。记住这种场景思路
  if (orderId.value) {
    return false
  }
})

//用户引导
// 知识点：推荐使用userouter的方式引入
const router = useRouter()
const onBeforeClose = () => {
  showConfirmDialog({
    title: '温馨提示',
    message: '支付未完成，是否确认退出？',
    confirmButtonText: '继续支付',
    cancelButtonText: '放弃支付',
  }).catch(() => {
    // 清除订单id，让路由可跳转
    orderId.value = ''
    router.push('/user/consult')
    return true
  })
}

// 确认支付
const pay = async () => {
  if (selectedPayType.value === undefined) return
  showLoadingToast({
    message: '跳转支付',
    duration: 0,
    forbidClick: true,
  })
  // 调用支付接口
  const res = await getConsultOrderPayUrl({
    orderId: orderId.value,
    paymentMethod: selectedPayType.value,
    // 支付成功的跳转地址，给后端用的（支付失败的跳转在路由独享守卫中配置）
    payCallback: 'http://localhost:5173/room', // 知识点【跨域】：这里的回调地址必须是后端允许的地址，否则会报跨域错误
  })
  // 跳转到支付链接进行支付
  window.location.href = res.data.payUrl
}

// 知识点【ts的类型】：可以通过keyof关键字获取某个类型的所有key，组成一个联合类型，如下面的key取值可以是PartialConsult的任意一个字段，这样定义后ctrl+i有提示
type Key = keyof PartialConsult
onMounted(() => {
  // 判断问诊信息是否完整（其实感觉直接判断本地的问诊对象是否有内容也行，不用这么麻烦）
  const validKeys: Key[] = [
    'type',
    'illnessType',
    'depId',
    'illnessDesc',
    'illnessTime',
    'consultFlag',
    'patientId',
  ]
  const valid = validKeys.every((key) => store.consult[key] !== undefined)
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
      closeOnPopstate: false,
    }).then(() => {
      router.push('/')
    })
  }

  getPayINfo()
  getUserInfo()
})
</script>

<template>
  <!-- 知识点：避免还没有数据就加载了元素，页面展示不友好 -->
  <div class="consult-pay-page" v-if="payInfo && userInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction.toFixed(2)}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction.toFixed(2)}`" />
      <van-cell title="实付款" :value="`-¥${payInfo.actualPayment.toFixed(2)}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${userInfo.name} | ${userInfo.gender ? '男' : '女'} | ${userInfo.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="onSubmit"
      :loading="isLoading"
    />
    <!-- 支付抽屉 -->
    <!-- 知识点：close-on-popstate	属性，可以控制在页面返回的时候也不关闭组件，其他组件也可能有类似功能，注意根据场景使用 -->
    <van-action-sheet
      :before-close="onBeforeClose"
      :closeable="false"
      :close-on-popstate="false"
      v-model:show="showActionSheet"
      title="标题"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="selectedPayType = 0">
            <template #icon><svg-icon name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="selectedPayType === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="selectedPayType = 1">
            <template #icon><svg-icon name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="selectedPayType === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-action-sheet>
  </div>
  <!-- 知识点【vant组件】】：骨架屏幕，当某个页面数据需要加载比较久才出来，可以先展示骨架屏 -->
  <van-skeleton v-else title :row="10" style="margin-top: 40px" />
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  ::v-deep() {
    .van-cell {
      align-items: center;
      .custom-svg-icon {
        margin-right: 10px;
        font-size: 18px;
      }
      .van-checkbox :deep(.van-checkbox__icon) {
        font-size: 16px;
      }
    }
  }
}
</style>
